package org.example.juc.condition;

import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author songyafei
 */
public class Producer implements Runnable{

    private Queue<String> queue ;
    private  int maxSize;
    private Lock lock;
    private Condition condition;


    public Producer(Queue<String> queue, int maxSize, Lock lock, Condition condition) {
        this.queue = queue;
        this.maxSize = maxSize;
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        int i = 0;
        while(true){
            i++;
            lock.lock();
            while (queue.size()==maxSize){

                try {
                    condition.await();//生产者等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("队列满了，生产者等待");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            queue.add("Producer消息"+i);
            System.out.println("生产者生产消息:{"+i+"}");
            condition.signal();//唤醒阻塞状态的消费者
            lock.unlock();
        }
    }
}
